<template>
  <div class="past-exam-detail-container">
    <div class="header-section">
      <el-button type="primary" plain class="back-btn" @click="goBackToPastList">
        <i class="el-icon-arrow-left"></i> 返回考试记录
      </el-button>
      <h1>{{ examTitle }}</h1>
    </div>

    <div class="content-container">
      <!-- 考试摘要信息 -->
      <div class="summary-card" ref="summaryCard">
        <div class="summary-item">
          <span class="summary-label">试卷总分</span>
          <span class="summary-value">{{ detailData.totalScore }}分</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">你的得分</span>
          <span class="summary-value">{{ detailData.userScore }}分</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">选择题得分</span>
          <span class="summary-value">{{ detailData.choiceScore }}分</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">填空题得分</span>
          <span class="summary-value">{{ detailData.fillBlankScore }}分</span>
        </div>
      </div>
      
      <!-- 题型导航栏 -->
      <div class="question-type-nav" :class="{ 'fixed-nav': isNavFixed }" ref="navElement">
        <div class="nav-inner">
          <el-tabs v-model="activeType" class="centered-tabs">
            <el-tab-pane 
              v-if="detailData.choiceQuestions?.length > 0" 
              label="选择题" 
              name="choice"
            >
              <template #label>
                <span class="type-tab-label">
                  <i class="el-icon-tickets"></i> 选择题 ({{ detailData.choiceQuestions.length }})
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane 
              v-if="detailData.fillBlankQuestions?.length > 0" 
              label="填空题" 
              name="fillBlank"
            >
              <template #label>
                <span class="type-tab-label">
                  <i class="el-icon-edit-outline"></i> 填空题 ({{ detailData.fillBlankQuestions.length }})
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane 
              v-if="detailData.subjectiveQuestions?.length > 0" 
              label="主观题" 
              name="subjective"
            >
              <template #label>
                <span class="type-tab-label">
                  <i class="el-icon-document"></i> 主观题 ({{ detailData.subjectiveQuestions.length }})
                </span>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 选择题部分 -->
      <div v-if="activeType === 'choice' && detailData.choiceQuestions?.length > 0" class="results-container">
        <h2 class="section-title">一、选择题</h2>
        <div v-for="(question, index) in detailData.choiceQuestions" :key="'choice-' + index" class="result-card">
          <div class="result-header">
            <el-tag type="info" size="small">选择题</el-tag>
            <el-tag :type="question.isCorrect ? 'success' : 'danger'" size="small">
              {{ question.isCorrect ? '正确' : '错误' }}
            </el-tag>
            <el-tag type="info" size="small">{{ question.score || 5 }}分</el-tag>
            <div class="favorite-star" @click="toggleFavorite(question)">
              <i 
                v-if="!question.loading"
                :class="question.isFavorite ? 'el-icon-star-on' : 'el-icon-star-off'" 
                :style="{ color: question.isFavorite ? '#ffc107' : '#c0c4cc' }"
              ></i>
              <i v-else class="el-icon-loading"></i>
              <span class="favorite-text">{{ question.isFavorite ? '已收藏' : '收藏' }}</span>
            </div>
          </div>
          <div class="question-content">
            <span class="question-number">{{ index + 1 }}.</span>
            <div v-html="formatQuestionContent(question.content)" class="question-text"></div>
          </div>

          <div class="choices-container">
            <div v-for="(option, key) in parseOptions(question.options)" 
                 :key="key"
                 class="choice-item"
                 :class="{
                   'user-answer': key === question.userAnswer,
                   'correct-answer': key === question.correctAnswer,
                   'correct-and-selected': key === question.userAnswer && key === question.correctAnswer
                 }">
              <span class="option-label">{{ key }}.</span>
              <span class="option-text" v-html="formatQuestionContent(option)"></span>
            </div>
          </div>

          <div class="answer-container">
            <div class="analysis-row">
              <span class="answer-label">你的答案：</span>
              <span class="user-answer">{{ question.userAnswer || '未作答' }}</span>
            </div>
            <div class="analysis-row">
              <span class="answer-label">正确答案：</span>
              <span class="correct-answer">{{ question.correctAnswer }}</span>
            </div>
            <div v-if="question.analysis" class="analysis-row">
              <span class="answer-label">解析：</span>
              <span class="analysis-content" v-html="formatQuestionContent(question.analysis)"></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 填空题部分 -->
      <div v-if="activeType === 'fillBlank' && detailData.fillBlankQuestions?.length > 0" class="results-container">
        <h2 class="section-title">二、填空题</h2>
        <div v-for="(question, index) in detailData.fillBlankQuestions" :key="'fill-' + index" class="result-card">
          <div class="result-header">
            <el-tag type="info" size="small">填空题</el-tag>
            <el-tag :type="question.isCorrect ? 'success' : 'danger'" size="small">
              {{ question.isCorrect ? '正确' : '错误' }}
            </el-tag>
            <el-tag type="info" size="small">{{ question.score || 5 }}分</el-tag>
            <div class="favorite-star" @click="toggleFavorite(question)">
              <i 
                v-if="!question.loading"
                :class="question.isFavorite ? 'el-icon-star-on' : 'el-icon-star-off'" 
                :style="{ color: question.isFavorite ? '#ffc107' : '#c0c4cc' }"
              ></i>
              <i v-else class="el-icon-loading"></i>
              <span class="favorite-text">{{ question.isFavorite ? '已收藏' : '收藏' }}</span>
            </div>
          </div>
          <div class="question-content">
            <span class="question-number">{{ index + 1 }}.</span>
            <div v-html="formatQuestionContent(question.content)" class="question-text"></div>
          </div>

          <div v-if="question.questionType === 'fill_in_the_blank'" class="blanks-container">
            <div v-for="(blank, idx) in parseBlanks(question.blanks)" :key="idx" class="blank-item">
              <span class="blank-label">空{{ idx + 1 }}：</span>
              <span class="blank-answer" v-html="formatQuestionContent(blank.answer)"></span>
            </div>
          </div>

          <div class="answer-container">
            <div class="analysis-row">
              <span class="answer-label">你的答案：</span>
              <span class="user-answer" v-html="formatQuestionContent(question.userAnswer || '未作答')"></span>
            </div>
            <div class="analysis-row">
              <span class="answer-label">正确答案：</span>
              <span class="correct-answer" v-html="formatQuestionContent(question.correctAnswer || '暂无答案')"></span>
            </div>
            <div v-if="question.analysis || question.fillBlankQuestion?.analysis" class="analysis-row">
              <span class="answer-label">解析：</span>
              <span class="analysis-content" v-html="formatQuestionContent(question.analysis || question.fillBlankQuestion?.analysis || '暂无解析')"></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 主观题部分 -->
      <div v-if="activeType === 'subjective' && detailData.subjectiveQuestions?.length > 0" class="results-container">
        <h2 class="section-title">三、主观题</h2>
        <div v-for="(question, index) in detailData.subjectiveQuestions" :key="'subjective-' + index" class="result-card">
          <div class="result-header">
            <el-tag type="info" size="small">主观题</el-tag>
            <el-tag type="warning" size="small">待批改</el-tag>
            <el-tag type="info" size="small">{{ question.score || 0 }}分</el-tag>
            <div class="favorite-star" @click="toggleFavorite(question)">
              <i 
                v-if="!question.loading"
                :class="question.isFavorite ? 'el-icon-star-on' : 'el-icon-star-off'" 
                :style="{ color: question.isFavorite ? '#ffc107' : '#c0c4cc' }"
              ></i>
              <i v-else class="el-icon-loading"></i>
              <span class="favorite-text">{{ question.isFavorite ? '已收藏' : '收藏' }}</span>
            </div>
          </div>
          <div class="question-content">
            <span class="question-number">{{ index + 1 }}.</span>
            <div v-html="formatQuestionContent(question.content)" class="question-text"></div>
          </div>

          <div class="answer-container">
            <div class="analysis-row">
              <span class="answer-label">你的答案：</span>
              <div class="user-answer" v-html="formatQuestionContent(question.userAnswer || '未作答')"></div>
            </div>
            <div class="analysis-row">
              <span class="answer-label">参考答案：</span>
              <div class="correct-answer" v-html="formatQuestionContent(question.correctAnswer || '暂无答案')"></div>
            </div>
            <div v-if="question.analysis || question.subjectiveQuestion?.analysis" class="analysis-row">
              <span class="answer-label">解析：</span>
              <div class="analysis-content" v-html="formatQuestionContent(question.analysis || question.subjectiveQuestion?.analysis || '暂无解析')"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/store/user'

// 导入KaTeX和markdown-it相关库
import 'katex/dist/katex.min.css';
import katex from 'katex';
import MarkdownIt from 'markdown-it';
import markdownItKatex from 'markdown-it-katex';

export default {
  name: 'PastExamDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const recordId = route.params.recordId
    const userStore = useUserStore()

    // 配置markdown-it和KaTeX
    const md = new MarkdownIt({
      html: true,        // 允许HTML标签
      breaks: true,      // 转换换行符
      linkify: true      // 自动转换链接
    }).use(markdownItKatex, {
      // KaTeX配置选项
      throwOnError: false,
      errorColor: '#cc0000',
      strict: false,
      trust: true,
      output: 'html'
    });

    // 格式化题目内容 - 使用KaTeX和markdown-it处理
    const formatQuestionContent = (content) => {
      if (!content) return '';
      
      try {
        // 预处理内容
        let processedContent = content
          .replace(/\\n/g, '\n')  // 处理换行符
          .replace(/\\\$/g, '###DOLLAR###')  // 临时替换转义的美元符号
          .replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
            // 处理块级数学公式 $$...$$
            try {
              return katex.renderToString(formula.trim(), {
                displayMode: true,
                throwOnError: false,
                strict: false,
                trust: true
              });
            } catch (error) {
              console.warn('KaTeX block formula error:', error, 'Formula:', formula);
              return `<span class="katex-error">$$${formula}$$</span>`;
            }
          })
          .replace(/\$([^$\n]+)\$/g, (match, formula) => {
            // 处理行内数学公式 $...$
            try {
              return katex.renderToString(formula.trim(), {
                displayMode: false,
                throwOnError: false,
                strict: false,
                trust: true
              });
            } catch (error) {
              console.warn('KaTeX inline formula error:', error, 'Formula:', formula);
              return `<span class="katex-error">$${formula}$</span>`;
            }
          })
          .replace(/###DOLLAR###/g, '$');  // 恢复转义的美元符号
        
        // 使用markdown-it处理其他格式
        const htmlContent = md.render(processedContent);
        
        return htmlContent;
      } catch (error) {
        console.error('formatQuestionContent error:', error);
        return content.replace(/\\n/g, '<br>');
      }
    };
    
    const goBackToPastList = () => {
      router.push({
        name: 'TrainingRecord',
        query: { tab: 'pastExam' }
      })
    }

    const detailData = ref({
      examInfo: {},
      choiceQuestions: [],
      fillBlankQuestions: [],
      subjectiveQuestions: [],
      choiceScore: 0,
      fillBlankScore: 0,
      subjectiveScore: 0,
      totalScore: 0,
      userScore: 0
    })

    const loading = ref(false)
    const activeType = ref('choice') // 当前激活的题型
    const isNavFixed = ref(false) // 导航栏是否固定
    const navElement = ref(null) // 导航栏DOM元素引用
    const summaryCard = ref(null) // 概览卡片DOM元素引用

    const examTitle = computed(() => {
      if (detailData.value.examInfo) {
        return `${detailData.value.examInfo.examType} ${detailData.value.examInfo.examYear}`
      }
      return '真题考试详情'
    })

    const fetchExamDetail = async () => {
      try {
        loading.value = true
        const response = await axios.get(`/api/past-exams/detail/${recordId}`)
        
        // 从后端获取各题型得分
        const choiceScore = response.data.choiceScore || 0
        const fillBlankScore = response.data.fillBlankScore || 0
        
        detailData.value = {
          examInfo: response.data.examInfo || {},
          choiceQuestions: (response.data.choiceQuestions || []).map(question => ({
            ...question,
            loading: false,
            isFavorite: question.isFavorite || false
          })),
          fillBlankQuestions: (response.data.fillBlankQuestions || []).map(question => ({
            ...question,
            loading: false,
            isFavorite: question.isFavorite || false
          })),
          subjectiveQuestions: (response.data.subjectiveQuestions || []).map(question => ({
            ...question,
            loading: false,
            isFavorite: question.isFavorite || false
          })),
          totalScore: 80, // 固定试卷总分
          userScore: Math.round(choiceScore + fillBlankScore), // 确保整数
          choiceScore: Math.round(choiceScore),
          fillBlankScore: Math.round(fillBlankScore),
          subjectiveScore: 0 // 主观题不计分
        }

        // 设置默认激活的题型
        if (detailData.value.choiceQuestions?.length > 0) {
          activeType.value = 'choice'
        } else if (detailData.value.fillBlankQuestions?.length > 0) {
          activeType.value = 'fillBlank'
        } else if (detailData.value.subjectiveQuestions?.length > 0) {
          activeType.value = 'subjective'
        }
      } catch (error) {
        console.error('加载失败:', error)
        ElMessage.error('加载失败: ' + (error.response?.data?.message || error.message))
      } finally {
        loading.value = false
      }
    }

    const parseBlanks = (blanks) => {
      if (!blanks) return []
      try {
        return typeof blanks === 'string' ? JSON.parse(blanks) : blanks
      } catch (e) {
        console.error('解析填空题空白失败:', e)
        return []
      }
    }

    // 检测内容是否已经包含选项标识符
    const hasOptionLabels = (content) => {
      if (!content) return false;
      // 检查是否包含 "A." "B." "C." "D." 这样的模式
      return /^[A-Z]\.\s/.test(content.trim());
    }

    // 清理选项内容，移除开头的选项标识符
    const cleanOptionContent = (content) => {
      if (!content) return '';
      // 移除开头的 "A." "B." "C." "D." 等标识符
      return content.replace(/^[A-Z]\.\s*/, '').trim();
    }

    const parseOptions = (options) => {
      if (!options) return {}
      try {
        let parsedOptions = {};
        
        // 如果已经是对象直接使用
        if (typeof options === 'object' && !Array.isArray(options)) {
          parsedOptions = options
        }
        // 如果是字符串尝试解析
        else if (typeof options === 'string') {
          const parsed = JSON.parse(options)
          // 如果解析后是数组，转换为对象格式 A、B、C、D
          if (Array.isArray(parsed)) {
            parsedOptions = parsed.reduce((acc, opt, idx) => {
              acc[String.fromCharCode(65 + idx)] = opt
              return acc
            }, {})
          } else {
            parsedOptions = parsed
          }
        }
        // 如果是数组转换为对象
        else if (Array.isArray(options)) {
          parsedOptions = options.reduce((acc, opt, idx) => {
            acc[String.fromCharCode(65 + idx)] = opt
            return acc
          }, {})
        }
        
        // 清理选项内容，避免重复的字母标识
        const cleanedOptions = {};
        Object.keys(parsedOptions).forEach(key => {
          const content = parsedOptions[key];
          if (hasOptionLabels(content)) {
            // 如果内容已经包含选项标识符，清理它
            cleanedOptions[key] = cleanOptionContent(content);
          } else {
            // 否则直接使用原内容
            cleanedOptions[key] = content;
          }
        });
        
        return cleanedOptions;
      } catch (e) {
        console.error('解析选项失败:', options, e)
        return {}
      }
    }

    // 处理滚动事件
    const handleScroll = () => {
      if (!navElement.value || !summaryCard.value) return
      
      const navRect = navElement.value.getBoundingClientRect()
      const summaryRect = summaryCard.value.getBoundingClientRect()
      const headerHeight = 64 // 导航栏高度
      
      // 当导航栏滚动到距离顶部等于导航栏高度时固定
      // 并且只有当概览卡片完全滚出视口时才固定
      isNavFixed.value = navRect.top <= headerHeight && summaryRect.bottom <= headerHeight
    }

    const toggleFavorite = async (question) => {
      try {
        // 设置加载状态
        question.loading = true;
        
        const newStatus = !question.isFavorite;
        await axios.post('/api/past-exams/favorite', {
          questionId: question.questionId,
          isFavorite: newStatus,
          userId: userStore.userId
        }, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        question.isFavorite = newStatus;
        ElMessage.success(newStatus ? '已收藏题目' : '已取消收藏');
      } catch (error) {
        console.error('收藏操作失败:', error);
        ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message));
      } finally {
        question.loading = false;
      }
    };

    onMounted(() => {
      fetchExamDetail()
      window.addEventListener('scroll', handleScroll, { passive: true })
    })

    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll)
    })

    return {
      detailData,
      loading,
      examTitle,
      parseOptions,
      parseBlanks,
      goBackToPastList,
      activeType,
      isNavFixed,
      navElement,
      summaryCard,
      toggleFavorite,
      formatQuestionContent
    }
  }
}
</script>

<style scoped>
.past-exam-detail-container {
  max-width: 900px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  position: relative;
}

.header-section {
  position: relative;
  text-align: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.back-btn {
  position: absolute;
  left: 0;
  top: 5px;
  padding: 8px 15px;
}

h1 {
  color: #303133;
  font-size: 20px;
  margin: 0;
  padding: 10px 0;
}

.content-container {
  margin-top: 20px;
}

.summary-card {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30px;
  padding: 20px 15px;
  background: linear-gradient(135deg, #f0f7ff, #e6f7ff);
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.1);
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.summary-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

.question-type-nav {
  margin: 20px auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: none;
  max-width: 860px;
  width: calc(100% - 40px);
}

.nav-inner {
  display: flex;
  justify-content: center;
}

.centered-tabs {
  display: inline-flex;
}

.question-type-nav.fixed-nav {
  position: fixed;
  top: 64px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
  margin: 0;
  border-radius: 8px;
  padding: 10px 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: calc(100% - 40px);
  max-width: 900px;
}

.question-type-nav.fixed-nav ~ .results-container {
  padding-top: 60px;
}

.type-tab-label {
  display: flex;
  align-items: center;
  gap: 5px;
}

.results-container {
  margin-top: 20px;
}

.section-title {
  color: #409EFF;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
  margin: 20px 0;
}

.result-card {
  margin-bottom: 25px;
  padding: 20px;
  border-radius: 8px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.result-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.result-header {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
  align-items: center;
}

.question-content {
  font-size: 16px;
  margin-bottom: 15px;
  line-height: 1.7;
  color: #303133;
  display: flex;
  align-items: flex-start;
}

.question-number {
  font-weight: 600;
  margin-right: 5px;
  flex-shrink: 0;
}

.question-text {
  flex: 1;
}

.choices-container {
  margin: 15px 0;
  padding-left: 10px;
  border-left: 3px solid #e6f7ff;
}

.choice-item {
  margin: 10px 0;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f9fbfd;
  line-height: 1.6;
  border: 1px solid #ebeef5;
  display: flex;
  align-items: baseline;
}

.choice-item.user-answer {
  background-color: #fff1f0;
  border-color: #ffccc7;
}

.choice-item.correct-answer {
  background-color: #f6ffed;
  border-color: #b7eb8f;
}

.choice-item.correct-and-selected {
  background-color: #d9f7be;
  border-color: #95de64;
}

.answer-container {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8fafc;
  border-radius: 6px;
}

.analysis-row {
  margin-bottom: 12px;
  display: flex;
  align-items: baseline;
}

.analysis-row:last-child {
  margin-bottom: 0;
}

.answer-label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  line-height: 1.6;
  flex-shrink: 0;
}

.user-answer {
  color: #ff4d4f;
  font-weight: 500;
  flex: 1;
  line-height: 1.6;
}

.correct-answer {
  color: #52c41a;
  font-weight: 500;
  flex: 1;
  line-height: 1.6;
}

.analysis-content {
  color: #606266;
  line-height: 1.6;
  flex: 1;
}

.option-label {
  font-weight: bold;
  margin-right: 10px;
  flex-shrink: 0;
  line-height: 1.6;
}

.option-text {
  flex: 1;
  line-height: 1.6;
}

.blanks-container {
  margin: 15px 0;
}

.blank-item {
  margin: 10px 0;
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: baseline;
}

.blank-label {
  font-weight: bold;
  margin-right: 8px;
  color: #409EFF;
  flex-shrink: 0;
  line-height: 1.6;
}

.blank-answer {
  color: #67C23A;
  flex: 1;
  line-height: 1.6;
}

/* 收藏按钮样式 */
.favorite-star {
  margin-left: auto;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.favorite-star:hover {
  background-color: #f5f7fa;
}

.favorite-star i {
  font-size: 18px;
  margin-right: 4px;
  transition: all 0.3s;
}

.favorite-star .el-icon-star-on {
  color: #ffc107;
}

.favorite-star .el-icon-star-off {
  color: #c0c4cc;
}

.favorite-star .el-icon-loading {
  color: #909399;
}

.favorite-star:hover .el-icon-star-off {
  color: #ffc107;
}

.favorite-text {
  font-size: 12px;
  color: #606266;
}

/* KaTeX样式优化 */
:deep(.katex) {
  font-size: 1.1em;
  line-height: 1.5;
  overflow-x: auto;
  overflow-y: hidden;
  max-width: 100%;
}

:deep(.katex-display) {
  margin: 1em 0;
  text-align: center;
  overflow-x: auto;
  overflow-y: hidden;
  padding: 0.5em 0;
}

:deep(.katex-error) {
  color: #d32f2f;
  background: #ffebee;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

/* 确保KaTeX在所有容器中都能正确显示 */
:deep(.katex .mord),
:deep(.katex .mrel),
:deep(.katex .mop),
:deep(.katex .mbin),
:deep(.katex .mpunct),
:deep(.katex .mopen),
:deep(.katex .mclose) {
  color: inherit;
}

@media (max-width: 768px) {
  .past-exam-detail-container {
    padding: 15px;
  }
  
  .summary-card {
    flex-direction: column;
    gap: 20px;
  }
  
  .result-header {
    gap: 8px;
  }

  .question-type-nav {
    width: calc(100% - 30px);
  }

  .question-type-nav.fixed-nav {
    top: 60px;
    padding: 10px 15px;
    width: calc(100% - 30px);
  }

  .question-type-nav.fixed-nav ~ .results-container {
    padding-top: 50px;
  }
  
  .favorite-text {
    display: none;
  }

  .question-content {
    flex-direction: column;
  }

  .question-number {
    margin-bottom: 5px;
  }

  .analysis-row {
    flex-direction: column;
    gap: 5px;
  }

  .answer-label {
    min-width: auto;
  }

  .choice-item {
    flex-direction: column;
    gap: 5px;
  }

  .option-label {
    margin-bottom: 5px;
  }

  .blank-item {
    flex-direction: column;
    gap: 5px;
  }

  .blank-label {
    margin-bottom: 5px;
  }
}
</style>